# -*- coding: utf-8 -*-
import hashlib
import json
from collections import OrderedDict

import requests
from django.conf import settings
from django.template import Context
from django.template.loader import get_template

from async import async_job
from common.cache import redis_cache
from common.channel.pay import check_channel_order
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError
from common.utils.ip_address import check_valid_ip_address
from common.utils.qr import make_code
from common.utils.tz import local_now

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    'Pro88882019042510001318': {
        #  凯硕宝支付 支付宝原生 3.5  支付宝100-5000   loki
        #  凯硕宝支付 微信4          微信扫码300-5000  loki
        'payKey': 'd5e479b2d01e407fb8907360880e7aa2',
        'paySecret': '8361a09a1ddf4aaab2b5d6e147dffcb2',
        'gateway': 'https://gateway.lyzx8.cn/cnpPay/initPay',
        'query_gateway': 'https://gateway.lyzx8.cn/query/singleOrder',
    },
}


def _get_pay_key(mch_id):
    return APP_CONF[mch_id]['payKey']


def _get_pay_secret(mch_id):
    return APP_CONF[mch_id]['paySecret']


def _get_app_id(mch_id):
    return APP_CONF[mch_id]['appId']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _get_query_gateway(mch_id):
    return APP_CONF[mch_id]['query_gateway']


def _gen_sign(s):
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().upper()
    return sign


def _get_type(service):
    '''
    支付宝T0扫码支付	20000303
    支付宝H5/WAP T0支付	20000203
    支付宝D0扫码支付	20000302
    支付宝T1扫码支付	20000301
    支付宝H5/WAP D0支付	20000202
    支付宝H5/WAP T1支付	20000201

    微信T0扫码支付	10000103
    微信H5/WAP T0支付	10000203
    微信D0扫码支付	10000102
    微信T1扫码支付	10000101
    微信H5/WAP D0支付	10000202
    微信H5/WAP T1支付	10000201
    '''
    if service == 'wechat_scan_t0':
        return '10000103'
    elif service == 'wechat_wap_t0':
        return '10000203'
    elif service == 'alipay_scan_t0':
        return '20000303'
    elif service == 'alipay_wap_t0':
        return '20000203'
    else:
        return '20000303'


def generate_sign(parameter, key):
    s = ''
    for k in sorted(parameter.keys()):
        if k != 'sign' and parameter[k] != '':
            s += '%s=%s&' % (k, parameter[k])
    s += 'paySecret=%s' % key
    return _gen_sign(s)


def _get_device_ip(info):
    try:
        extra = json.loads(info['extra'])
    except:
        extra = {}
    user_info = extra.get('user_info', {})
    return user_info.get('device_ip') or '127.0.0.1'


def gen_notify_sign(d, key):
    s = ''
    for k in sorted(d.keys()):
        s += '%s' % d[k]
    s += '%s' % key
    return _gen_sign(s)


def verify_notify_sign(params, key):
    sign = params['sign']
    params.pop('sign')
    calculated_sign = generate_sign(params, key)
    if sign.upper() != calculated_sign.upper():
        _LOGGER.info("kaisuobaopay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def _get_str(s, start, end):
    p1 = s.index(start)
    p2 = s.index(end, p1 + len(start))
    if p2 > p1:
        return s[p1 + len(start): p2]
    else:
        return ''


def create_charge(pay, pay_amount, info):
    app_id = info['app_id']
    pay_key = _get_pay_key(app_id)
    service = info.get('service')
    paySecret = _get_pay_secret(app_id)
    parameter_dict = OrderedDict((
        ('payKey', pay_key),
        ('orderPrice', '%.2f' % pay_amount),
        ('outTradeNo', str(pay.id)),
        ('productType', _get_type(service)),
        ('orderTime', local_now().strftime("%Y%m%d%H%M%S")),
        ('productName', 'KSB'),
        ('orderIp', _get_device_ip(info)),
        (
            'returnUrl',
            '{}/pay/api/{}/kaisuobaopay/{}'.format(settings.NOTIFY_PREFIX, settings.RETURN_PATH, str(pay.id))),
        ('notifyUrl', '{}/pay/api/{}/kaisuobaopay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
        ('remark', 'charge'),
    ))
    parameter_dict['sign'] = generate_sign(parameter_dict, paySecret)
    _LOGGER.info("kaisuobaopay create: %s, order_id is: %s", json.dumps(parameter_dict), parameter_dict['outTradeNo'])
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_get_gateway(app_id), data=parameter_dict, headers=headers, timeout=3)
    _LOGGER.info("kaisuobaopay create rsp data: %s %s", response.status_code, response.text)
    verify_notify_sign(json.loads(response.text), paySecret)
    pay_message = json.loads(response.text)['payMessage']

    # if service == 'wechat_scan_t0':
    #     try:
    #         template_data = {'base64_img': make_code(pay_message), 'amount': pay_amount}
    #         t = get_template('qr_wechat_kaisuobao.html')
    #         html = t.render(Context(template_data))
    #         cache_id = redis_cache.save_html(pay.id, html)
    #         _LOGGER.info("wenfupay create_url: %s, pay.id: %s", settings.PAY_CACHE_URL + cache_id, pay.id)
    #         return {'charge_info': settings.PAY_CACHE_URL + cache_id}
    #     except:
    #         return {'charge_info': pay_message}
    # elif service == 'alipay_scan_t0':
    #     try:
    #         template_data = {'base64_img': make_code(pay_message), 'amount': pay_amount}
    #         t = get_template('qr_alipay_kaisuobao.html')
    #         html = t.render(Context(template_data))
    #         cache_id = redis_cache.save_html(pay.id, html)
    #         _LOGGER.info("wenfupay create_url: %s, pay.id: %s", settings.PAY_CACHE_URL + cache_id, pay.id)
    #         return {'charge_info': settings.PAY_CACHE_URL + cache_id}
    #     except:
    #         return {'charge_info': pay_message}
    # else:
    #     return {'charge_info': _get_str(pay_message, '=\'', '\'')}

    if service not in ['wechat_scan_t0', 'alipay_scan_t0']:
        return {'charge_info': _get_str(pay_message, '=\'', '\'')}
    else:
        try:
            template_data = {'base64_img': make_code(pay_message), 'amount': pay_amount}
            if service == 'wechat_scan_t0':
                t = get_template('qr_wechat_kaisuobao.html')
            elif service == 'alipay_scan_t0':
                t = get_template('qr_alipay_kaisuobao.html')
            else:
                t = get_template('qr_alipay_kaisuobao.html')
            html = t.render(Context(template_data))
            cache_id = redis_cache.save_html(pay.id, html)
            _LOGGER.info("wenfupay create_url: %s, pay.id: %s", settings.PAY_CACHE_URL + cache_id, pay.id)
            return {'charge_info': settings.PAY_CACHE_URL + cache_id}
        except:
            return {'charge_info': pay_message}


# success
def check_notify_sign(request, app_id):
    paySecret = _get_pay_secret(app_id)
    data = dict(request.GET.iteritems())
    _LOGGER.info("kaisuobaopay notify data: %s, order_id is: %s", data, data['outTradeNo'])

    verify_notify_sign(data, paySecret)
    pay_id = data['outTradeNo']
    check_valid_ip_address(str(request.META['REMOTE_ADDR']), pay_id)
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s", data)
        raise ParamError('kaisuobaopay event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = str(data['tradeStatus'])
    trade_no = str(data['trxNo'])
    total_fee = float(data['orderPrice'])
    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }
    check_channel_order(pay_id, total_fee, app_id)
    # 【SUCCESS】交易成功
    # 【FAILED】交易失败
    # 【WAITING_PAYMENT】 等待支付
    if trade_status == 'SUCCESS':
        _LOGGER.info('kaisuobaopay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    ''' 查询订单 '''
    paySecret = _get_pay_secret(app_id)
    p_dict = OrderedDict((
        ('outTradeNo', pay_order.id),
        ('payKey', _get_pay_key(app_id)),
    ))
    p_dict['sign'] = generate_sign(p_dict, paySecret)
    _LOGGER.info('kaisuobaopay query data: %s, order_id is: %s', json.dumps(p_dict), p_dict['outTradeNo'])
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_get_query_gateway(app_id), data=p_dict, headers=headers, timeout=3)
    _LOGGER.info('kaisuobaopay query, %s', response.text)
    if response.status_code == 200:
        data = json.loads(response.text)
        mch_id = pay_order.mch_id
        trade_status = str(data['orderStatus'])
        total_fee = float(data['orderPrice'])
        trade_no = str(data['trxNo'])

        extend = {
            'trade_status': trade_status,
            'trade_no': trade_no,
            'total_fee': total_fee
        }
        # 【SUCCESS】：支付成功 【T0,T1】
        # 【FINISH】交易完成 【T1订单对账完成时返回该状态值】
        # 【FAILED】：支付失败
        # 【WAITING_PAYMENT】：等待支付
        if trade_status in ['SUCCESS', 'FINISH'] and total_fee > 0:
            _LOGGER.info('kaisuobaopay query order success, mch_id:%s pay_id:%s' % (mch_id, pay_order.id))
            res = order_db.add_pay_success(pay_order.mch_id, pay_order.id,
                                           total_fee, trade_no, extend)
            if res:
                # async notify
                async_job.notify_mch(pay_order.id)
